<?php

declare(strict_types=1);

namespace app\shop\controller\admin\app\mplive;

use sheep\controller\Backend;
use sheep\exception\SheepException;
use sheep\facade\Client;
use app\shop\model\app\mplive\Room as MpliveRoomModel;

/**
 * 小程序直播
 */
class Mplive extends Backend
{
    protected $wechat;

    public function initialize()
    {
        $service = new \app\shop\service\third\wechat\MiniProgram();
        $this->wechat = $service->wechat;
    }

    // 上传临时素材
    protected function uploadMedia($path)
    {
        $filesystem = config('filesystem.default');
        if ($filesystem !== 'local' || is_url($path)) {
            $response = Client::httpGet(domainurl($path));
            $body = $response->getBody()->getContents();    // 图片数据流
            $dir = runtime_path('storage' . DIRECTORY_SEPARATOR . 'temp');
            if (!is_dir($dir)) {
                @mkdir($dir, 0755, true);
            }
            $temp_path = $dir . $this->getBaseName($path);
            file_put_contents($temp_path, $body);
        } else {
            $temp_path = public_path() . $path;
        }

        if (!isset($temp_path) || empty($temp_path)) {
            throw new SheepException("上传失败，不是一个有效的文件: " . $path);
        }

        $media = $this->wechat->media;
        $res = $media->uploadImage($temp_path);
        @unlink($temp_path);        // 删除临时文件
        if (isset($res['media_id'])) {
            return $res['media_id'];
        }
        return '';
    }

    // 解析图片文件名
    private function getBaseName($path)
    {
        if (strpos($path, 'mmbiz.qpic.cn') !== false) {
            return DIRECTORY_SEPARATOR . gen_random_str(8) . '.jpg';
        }

        return basename($path);
    }

    // 转义直播错误信息
    protected function catchLiveError($response)
    {
        if (!isset($response['errcode'])) {
            throw new SheepException("未知错误");
        }

        $errorMap = MpliveRoomModel::ERR_CODE;
        if (isset($response['errcode']) && ($response['errcode'] !== 0 && $response['errcode'] !== 1001)) {
            if (isset($errorMap[$response['errcode']])) {
                throw new SheepException("{$errorMap[$response['errcode']]} [错误码: {$response['errcode']}]");
            } else {
                throw new SheepException("{$response['errmsg']} [错误码: {$response['errcode']}]");
            }
        }
    }
}
